package com.example.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.commons.utils.JwtTokenService;
import com.example.config.ResponseVO;
import com.example.pojo.Menu;
import com.example.pojo.User;
import com.example.service.UserRoleService;
import com.example.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/user")
@Api(tags = {"测试接口"})
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private UserRoleService userRoleService;

    @Resource
    private JwtTokenService jwtTokenService;

    @GetMapping("/userInfoList")
    @ApiOperation(value = "查询指定id的用户信息接口", notes = "查询指定id的用户信息接口")
    public ResponseEntity<ResponseVO<List<User>>> getUsers() {
        List<User> allUsers = userService.getAllUsers();
        if (!allUsers.isEmpty()) {
            return ResponseEntity.ok(new ResponseVO<>(HttpStatus.OK, "用户信息获取成功", allUsers));
        }
        return ResponseEntity.ok(new ResponseVO<>(HttpStatus.OK, "暂无用户数据", null));
    }

    @GetMapping("/userInfoListPage/{currentPage}/{limit}")
    public ResponseEntity<ResponseVO<IPage<User>>> getUsersPage(@PathVariable int currentPage, @PathVariable int limit) {
        IPage<User> usersPage = userService.getUsersPage(currentPage, limit);
        return ResponseEntity.ok(new ResponseVO<>(HttpStatus.OK, "用户信息获取成功", usersPage));
    }


    @GetMapping("/role/userPermission")
    public ResponseVO<User> getUserPermission(@RequestHeader(value = "Authorization", required = false) String authorizationHeader) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            // 如果Authorization Header不存在或者格式不正确，则返回401 Unauthorized
            return ResponseVO.error(HttpStatus.UNAUTHORIZED, "发送请求有误，请联系管理员");
        }
        String token = authorizationHeader.substring(7); // 去掉 "Bearer " 部分
        String usernameFromToken = jwtTokenService.getUsernameFromToken(token);
        return ResponseVO.success(userService.getUserBynameOne(usernameFromToken));
    }

    @GetMapping("/getUserByName/{currentPage}/{limit}/{username}")
    public ResponseEntity<ResponseVO<IPage<User>>> getUserByName(@PathVariable int currentPage, @PathVariable int limit, @PathVariable("username") String username) {
        IPage<User> userByname = userService.getUserByname(currentPage, limit, username);
        return ResponseEntity.ok(new ResponseVO<>(HttpStatus.OK, "用户信息获取成功", userByname));
    }

    @PostMapping("/login")
    public ResponseEntity<ResponseVO<String>> login(@RequestBody User user) {
        System.out.println(userService.login(user.getUsername(), user.getPassword()));
        if (userService.login(user.getUsername(), user.getPassword())) {
            // 生成token
            if (userService.getStateByName(user.getUsername())) {
                String token = jwtTokenService.generateToken(user.getUsername());
                return ResponseEntity.ok(new ResponseVO<>(HttpStatus.OK, null, token));
            } else {
                // 该账号被禁用，请联系管理员
                return ResponseEntity.ok(new ResponseVO<>(HttpStatus.FORBIDDEN, "该用户已被禁用", null));
            }
        } else {
            // 账号登录信息有误，请重新输入
            return ResponseEntity.ok(new ResponseVO<>(HttpStatus.NOT_FOUND, "账号登录信息有误", null));
        }
    }

    @PostMapping("/addUserInfo")
    public ResponseEntity<ResponseVO<String>> addUser(@RequestBody User user) {
        int i = userService.addUser(user);
        if (i > 0) {
            return ResponseEntity.ok(new ResponseVO<>(HttpStatus.OK, "用户添加成功", "success"));
        }
        return ResponseEntity.ok(new ResponseVO<>(HttpStatus.NOT_FOUND, "系统繁忙，请稍后再试", null));
    }

    @PostMapping("/deleteUserById/{deleteId}")
    public ResponseEntity<ResponseVO<String>> deleteUserById(@PathVariable("deleteId") int deleteId) {
        int resultRow = userService.deleteUser(deleteId);
        if (resultRow > 0) {
            return ResponseEntity.ok(new ResponseVO<>(HttpStatus.OK, "用户删除成功", "success"));
        }
        return ResponseEntity.ok(new ResponseVO<>(HttpStatus.NOT_FOUND, "系统繁忙，请稍后再试", null));
    }

    @GetMapping("/me")
    public ResponseEntity<User> getUsernameFromToken(@RequestHeader(value = "Authorization", required = false) String authorizationHeader) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            // 如果Authorization Header不存在或者格式不正确，则返回401 Unauthorized
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        String token = authorizationHeader.substring(7); // 去掉 "Bearer " 部分
        String usernameFromToken = jwtTokenService.getUsernameFromToken(token);
        // 获取用户信息
        User user = userService.getUserBynameOne(usernameFromToken);

        // 如果获取到用户，则以200 OK状态返回用户对象；否则，抛出异常或返回404 Not Found。
        if (user != null) {
            return ResponseEntity.ok(user);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    @PostMapping("/getMenuByUser")
    public List<Menu> getMenuByUser(@RequestBody User user) {
        return userService.getUserHaveMenu(user);
    }

    @DeleteMapping("/batchDeleteUser")
    public ResponseEntity<ResponseVO<String>> batchDeleteUser(@RequestParam List<Integer> userIdArr){
        try {
            int result = userService.batchDeleteUser(userIdArr);
            if(result>0){
                return ResponseEntity.ok(new ResponseVO<>(HttpStatus.OK,"删除成功"));
            }else{
                return ResponseEntity.ok(new ResponseVO<>(HttpStatus.BAD_REQUEST,"删除失败,请稍后再试"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(new ResponseVO<>(HttpStatus.BAD_REQUEST,"删除失败 " + e.getMessage()));
        }
    }

    @PostMapping("/changeStatus/{uId}/{uStatus}")
    public ResponseEntity<ResponseVO<String>> changeStatus(@PathVariable Integer uId,@PathVariable Integer uStatus){
        try {
            int result = userService.changeStatus(uId,uStatus);
            if(result>0){
                return ResponseEntity.ok(new ResponseVO<>(HttpStatus.OK, "修改状态成功", "success"));
            }else{
                return ResponseEntity.status(500).body(new ResponseVO<>(HttpStatus.BAD_REQUEST, "修改状态失败", "error"));
            }
        } catch (Exception e) {
            return ResponseEntity.status(500).body(new ResponseVO<>(HttpStatus.BAD_REQUEST, "修改状态失败", "error"));
        }
    }
}
